#region Using Statements
using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Tomahawk.Runtime.Rendering.Interfaces;
using Microsoft.Xna.Framework.Graphics;
using Tomahawk.Runtime.Rendering.Materials;
using Microsoft.Xna.Framework.Content;
#endregion

namespace Tomahawk.Runtime.Rendering.Objects
{
    /// <summary>
    /// This is a renderable primitive the draws a quad using a material
    /// </summary>
    public class MaterialQuad : MaterialEntity, IRenderable
    {
        string materialName;

        private VertexBuffer myVertices;
        private IndexBuffer myIndices;
        private VertexDeclaration declaration;
        SASMaterial material;

        /// <summary>
        /// Constructor
        /// </summary>
        public MaterialQuad(string materialName)
        {
            this.materialName = materialName;
        }

        /// <summary>
        /// Load Content: get the material, and create the quad mesh
        /// </summary>
        protected override bool OnLoad(GraphicsDevice graphics, ContentManager contentManager)
        {
            material = SASMaterialCollection.Load<SASMaterial>(this.materialName, contentManager);

            //create the quad
            VertexPositionTexture[] verts = {
		        new VertexPositionTexture(new Vector3(-0.5f, 0.5f, 0), new Vector2(0, 0)),
		        new VertexPositionTexture(new Vector3(0.5f, 0.5f, 0), new Vector2(1, 0)),		
		        new VertexPositionTexture(new Vector3(-0.5f, -0.5f, 0), new Vector2(0, 1)),	
		        new VertexPositionTexture(new Vector3(0.5f, -0.5f, 0), new Vector2(1, 1))
	        };

            int[] inds = { 0, 1, 2, 1, 3, 2 };

            myVertices = new VertexBuffer(
                graphics, typeof(VertexPositionTexture), 4,
                BufferUsage.WriteOnly);

            myVertices.SetData<VertexPositionTexture>(verts, 0, 4);

            myIndices = new IndexBuffer(
                graphics, typeof(int), 6,
                BufferUsage.WriteOnly);

            myIndices.SetData<int>(inds, 0, 6);

            declaration = new VertexDeclaration(graphics, VertexPositionTexture.VertexElements);

            return true;
        }

        /// <summary>
        /// Render the quad
        /// </summary>
        public void Render(ref Matrix worldMatrix, GraphicsDevice myDevice)
        {
            material.Update(Engine.Instance.EffectEnvironment);

            SASMaterial.Begin(myVertices, myIndices, 0, declaration, myDevice);
            material.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, 4, 0, 2, myDevice);
            SASMaterial.End();
        }
    }
}


